package com.zeroone.star.publish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zeroone.star.publish.entity.ModifyUserDTO;
import com.zeroone.star.publish.entity.User;
import com.zeroone.star.publish.mapper.UserMapper;
import com.zeroone.star.publish.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.mapstruct.Mapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Blob;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author car
 * @since 2024-03-02
 */
@Mapper(componentModel = "spring")
interface MyUserMapper {

}

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Integer insertUser(User user) {
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
//        user.setStatus(1);
//        user.setCreateTime(new D  ate());
        return userMapper.insert(user);
    }

    @Override
    public Integer deleteUser(Long id) {
        return userMapper.delete(new QueryWrapper<User>().eq("id", id));
    }

    @Override
    public User selectUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public Boolean login(Long id, String password) {
        User user = userMapper.selectById(id);
        if (user == null)
            return false;
        else {
            return passwordEncoder.matches(password, user.getPassword());
        }
    }

    @Override
    public User modifyUserPassword(Long id, String password, String newPassword) {
        User user = userMapper.selectById(id);
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (matches) {
            user.setPassword(passwordEncoder.encode(newPassword));
            userMapper.updateById(user);
        } else
            return null;
        return user;
    }

    @Override
    public List<User> batchSelectUser(List<Integer> userIdList) {
        List<User> users = userMapper.selectBatchIds(userIdList);
        return users;
    }

    @Override
    public Map<String, Integer> selectOneByName(String userName) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name", userName);
        HashMap<String, Integer> map = new HashMap<>();
        User user = userMapper.selectOne(wrapper);
        map.put(user.getName(), user.getId());
        return map;
    }

    /**
     * 更新用户头像
     *
     * @param userId     用户ID
     * @param avatarBlob 新的头像数据（Blob类型）
     * @return 更新成功返回1，否则返回0或其他异常代码
     */
    public Integer updateAvatar(Integer userId, Blob avatarBlob) {
        // 更新用户头像的逻辑
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatarBlob);
        return userMapper.updateById(user);
    }

    public boolean modifyUser(ModifyUserDTO modifiedUser) {
        // 通过id查询用户
        User existingUser = userMapper.selectById(modifiedUser.getId());

        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 将ModifyUserDTO中的信息更新到User对象中
        existingUser.setName(modifiedUser.getName());
        existingUser.setSex(modifiedUser.getSex());

        // 如果有生日信息，则更新生日
        if (modifiedUser.getBirthday() != null) {
            existingUser.setBirthday(Date.from(modifiedUser.getBirthday().atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }

        existingUser.setJob(modifiedUser.getJob());
        existingUser.setTelephone(modifiedUser.getTelephone());
        existingUser.setEmail(modifiedUser.getEmail());
        existingUser.setAddress(modifiedUser.getAddress());

        // 执行更新操作
        return userMapper.updateById(existingUser) > 0;
    }


}
